import socket
import cv2
import numpy as np
import time
import pydroid

def choose_camera(index):
    print("请选择摄像头类型：")
    print("1. 真实摄像头")
    print("2. 虚拟摄像头")
    print("3. 外置水下摄像头")
    # choice = input("输入1或2或3：")
    choice = index
    if choice == '1':
        return 0  # 真实摄像头的索引
    elif choice == '2':
        return 1  # 假设虚拟摄像头的索引为1
    elif choice == '3':
        return 2  # 假设外置水下摄像头的索引为2
    else:
        print("无效选择，默认使用真实摄像头")
        return 0  # 默认选择真实摄像头

def capture_android_camera():
    camera = pydroid.Camera()
    return camera

def client_program():
    host = '192.168.114.86'  # 服务器端的IP地址
    port = 5050  # 服务器端使用的端口号
    port2=5051

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((host, port))
    client_socket_img = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket_img.connect((host, port2))

    print(f"成功连接到服务器 {host}:{port}")

    camera_index = choose_camera(index = '1')

    if camera_index == 0:
        cap = cv2.VideoCapture(camera_index)  # 真实摄像头
    elif camera_index == 1:
        cap = cv2.VideoCapture(1)  # 虚拟摄像头
    elif camera_index == 2:
        cap = capture_android_camera()  # Android手机摄像头
    else:
        print("未选择有效的摄像头类型")
        return

    if not cap.isOpened():
        print("无法打开摄像头")
        client_socket.close()
        return

    try:
        while True:
            if camera_index == 2:  # 如果是Android手机摄像头
                frame = cap.read()
            else:
                ret, frame = cap.read()
                if not ret:
                    print("无法从摄像头读取帧")
                    break

            # 压缩图像
            encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
            result, img_encode = cv2.imencode('.jpg', frame, encode_param)
            data = np.array(img_encode)
            string_data = data.tobytes()

            # # 发送图像数据长度
            # client_socket.sendall(str(len(string_data)).ljust(16).encode('utf-8'))
            # # 发送图像数据
            # client_socket.sendall(string_data)

            # 发送图像数据长度
            client_socket_img.sendall(str(len(string_data)).ljust(16).encode('utf-8'))
            # 发送图像数据
            client_socket_img.sendall(string_data)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    except Exception as e:
        print(f"连接或发送数据时出现错误: {e}")
    finally:
        if camera_index == 2:  # 释放Android手机摄像头
            cap.release()
        client_socket.close()

if __name__ == '__main__':
    client_program()